<template>
  <div class="login-container">
    <van-form @submit="onSubmit">
      <div class="login-title">用户登录</div>
      <van-field
        v-model="username"
        name="用户名"
        label="用户名"
        placeholder="请输入用户名"
        :rules="[{ required: true, message: '请输入用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请输入密码' }]"
      />
      <div class="login-button">
        <van-button round block type="primary" native-type="submit"> 登录 </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Toast } from 'vant'
import axios from 'axios'
import { useRouter } from 'vue-router'

const username = ref('')
const password = ref('')
const router = useRouter()

// 登录逻辑
const onSubmit = () => {
  axios
    .post('http://localhost:1337/api/login', {
      username: username.value,
      password: password.value,
    })
    .then((response) => {
      if (response.data.success) {
        Toast.success('登录成功')
        // 登录成功后跳转到指定路由
        router.push('/home')
      } else {
        Toast.fail(response.data.message || '登录失败')
      }
    })
    .catch((error) => {
      Toast.fail('网络错误或服务器异常')
      console.error(error)
    })
}
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.login-button {
  margin-top: 20px;
}
</style>
